package com.prpat;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

import de.uniba.wiai.lspi.util.console.Command;

/**
 * A thread that finds the Node's successor and sends a 
 * {@link Message} to it
 * @author sas
 *
 */
class Client implements Runnable
{
	Message toSend;
	
	/**String holding the IP of the Node that will receive */
	String destination;
	
	Client( Message mes )
	{
		TaskAssistant.CLIENT_COUNT++;
		toSend = mes;
	}
	
	/**
	 * checks the IP of this Node's successor and assigns it to {@link destination}
	 */
	private void extractSuccessor() 
	{
		String str;
		try 
		{
			Command com = TaskAssistant.factory.createCommand("find");
			com.execute();
			str = com.toString();
			
			if(str != null)
			{
				str = str.substring(str.indexOf("//")+2, str.lastIndexOf("/"));
				if(str.contains(":"))
					str = str.substring(0, str.indexOf(":"));
				destination = str;
			}
			else
			{
				destination = null;
				TaskAssistant.display.append("This Node doesn't have successors\n");
			}

		}
		catch (Exception e) {
			destination = null;
			System.err.println("Client, extractSuccessor(), "+e.getMessage());

		}
	}
	
	public void run() 
	{
		extractSuccessor();
		
		if( destination != null )
		{
			try 
	        {
				Socket socket = new Socket(destination, TaskAssistant.CHAT_PORT);
				ObjectOutputStream reader = new ObjectOutputStream(socket.getOutputStream());
	            
	            reader.writeObject(toSend);
	            reader.flush();
	            socket.close();
	            
	            TaskAssistant.display.append("Sending to " + destination + " the following message \n");
	            TaskAssistant.display.append(toSend.getMessage() + "\n\n");
	        }
	        catch(IOException ex)
	        {
	        	System.err.println("Client, run(), ex" + ex.toString());
	        	TaskAssistant.display.append("Unable to connect to successor\n");
	        }
		}
		else
		{
			TaskAssistant.CONNECTED = false;
			TaskAssistant.ocExecuted("leaveN");
			TaskAssistant.display.append("Unable to connect to successor\n");	
		}
	}

}
